package com.smec.moblie.glocation;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.smec.moblie.activity.LoginActivity;
import com.smec.moblie.common.ConstValue;
import com.smec.moblie.control.LogControl;
import com.smec.moblie.control.PublicControl;
import com.smec.moblie.util.DateUtil;
import com.smec.moblie.util.FileUtil;
import com.smec.moblie.util.LocalLog;
import com.smec.remes.smecManager.location.SmecLocationBean;
import com.smec.remes.smecManager.location.SmecLocationManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.litepal.crud.DataSupport;

import java.util.List;

import okhttp3.Call;
import okhttp3.Request;

/**
 *
 */

public class LocationService extends Service implements ConstValue {

    private String postUrl = "http://bpmpublic.smec-cn.com:8011/SmecMntMapService/mnt_post_location_service";//正式环境


    private static final String TAG = "LocationService";

    private FileUtil fileUtil;
    private SmecLocationBean smecLocationBean=new SmecLocationBean();

    //声明AMapLocationClient类对象
    AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private Gson gson = new Gson();
//    private LocationBean locationBean;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private static StringBuffer logLocation = new StringBuffer();


    @Override
    public void onCreate() {
        super.onCreate();
        LogControl.log("start LocationService!");
        netThread.start();
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
//        mLocationOption.setOnceLocation(true);
        mLocationOption.setInterval(120 * 1000);//设置获取定位间隔
//        mLocationOption.setOnceLocationLatest(true);
        if (!isOPen()) {
            openGPS();
        }
        fileUtil = new FileUtil();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogControl.log("StartCommand LocationService!");
        getPosition();
        return super.onStartCommand(intent, flags, startId);

    }

    Handler netHandler = null;

    /**
     * 收发网络数据的线程
     */
    Thread netThread = new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            netHandler = new Handler() {
                public void dispatchMessage(Message msg) {
                    Bundle data = msg.getData();
                    switch (msg.what) {
                        case 0x1: //发送位置
                            try {
                                Double longitude = data.getDouble("longitude");
                                Double latitude = data.getDouble("latitude");
                                LogControl.log("~~location longitude = " + longitude + ",latitude = " + latitude);
                                SharedPreferences mySharedPreferences = getSharedPreferences("ElevatorSharedPreferences", LoginActivity.MODE_PRIVATE);
                                String USERNAME = mySharedPreferences.getString("USERNAME", "anonymous");
                                LocationBean locationBean = new LocationBean();
                                locationBean.setLat(latitude.toString());
                                locationBean.setLon(longitude.toString());
                                locationBean.setDevice(PublicControl.getDeviceId(getApplicationContext()));
                                locationBean.setUser(USERNAME);
                                locationBean.setType("m");
                                locationBean.setDate(System.currentTimeMillis() + "");
                                updateLocation(locationBean);

                                List<LocationBean> locationBeanList = DataSupport.findAll(LocationBean.class);
                                for (LocationBean locationBeanTemp : locationBeanList) {
                                    updateLocation(locationBeanTemp);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                Log.e("log", "~~上传坐标报错：" + e.getMessage());
                            }
                            break;

                    }
                }
            };
            Looper.loop();
        }
    };

    public void getPosition() {
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation == null) {
                LogControl.log("~~amapLocation is null!");
                return;
            }
            if (amapLocation.getErrorCode() != 0) {
                LogControl.log("~~amapLocation has exception errorCode:" + amapLocation.getErrorCode());
                return;
            }

            Double longitude = amapLocation.getLongitude();//获取经度
            Double latitude = amapLocation.getLatitude();//获取纬度
//            PublicControl.latitude = latitude;
//            PublicControl.longitude = longitude;

            logLocation.append(DateUtil.getTimeNow() + " longitude = " + longitude + " latitude = " + latitude + "\n");
            fileUtil.saveContentTosdCard("FastrepairLocationLog.txt", logLocation.toString());

            Message msg = new Message();
            Bundle data = new Bundle();
            data.putDouble("longitude", longitude);
            data.putDouble("latitude", latitude);
            /**
             * 左绪培2018-03-12 添加 坐标保存
             */
            smecLocationBean.setLongitude(longitude);
            smecLocationBean.setLatitude(latitude);
            SmecLocationManager.getInstance().setLocationBean(smecLocationBean);
            msg.setData(data);
            msg.what = 0x1;
            netHandler.sendMessage(msg);
        }

    };

    public void updateLocation(final LocationBean locationBean) {

        LocalLog.setDefalutTag("remes");
        LocalLog.setFileName("MaintanceLog");
        LocalLog.setLogPath(Environment.getExternalStorageDirectory().getPath());
        String jsonData = gson.toJson(locationBean);
        LocalLog.i("坐标接口上传数据：" + jsonData);
        OkHttpUtils.post().url(postUrl).addParams("lon", locationBean.getLon()).addParams("lat", locationBean.getLat())
                .addParams("user", locationBean.getUser()).addParams("type", locationBean.getType()).addParams("date", locationBean.getDate())
                .addParams("device", locationBean.getDevice()).addParams("version", PublicControl.getAppVersionName(getApplicationContext())).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                locationBean.saveIfNotExist();
            }

            @Override
            public void onResponse(String response, int id) {
                LogControl.log("~~~坐标返回 response = " + response);
                LocalLog.i("坐标接口返回：" + response);
                try {
                    Gson gson = new Gson();
                    LocationBackBean backBean = gson.fromJson(response.toString(), LocationBackBean.class);
                    if (backBean.getCode().equals("0")) {
                        LogControl.log("~~上传坐标成功");
                        try {
                            DataSupport.delete(LocationBean.class, locationBean.getId());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        locationBean.saveIfNotExist();
                    }

                } catch (Exception e) {
                    locationBean.saveIfNotExist();
                }
            }

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
            }

            @Override
            public void onAfter(int id) {
                super.onAfter(id);
            }


        });
    }

    /**
     * 强制帮用户打开GPS
     *
     * @param
     */
    public void openGPS() {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(getApplicationContext(), 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断GPS是否开启
     *
     * @param
     * @return true 表示开启
     */
    public final boolean isOPen() {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean gps = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (gps) {
            return true;
        }
        return false;
    }

}